package com.pospi.pospihold.ui.login_ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.pospi.pospihold.App;
import com.pospi.pospihold.R;
import com.pospi.pospihold.adapter.CashierLoginAdapter;
import com.pospi.pospihold.dao.GoodsDao;
import com.pospi.pospihold.dialog.WaitingDialog;
import com.pospi.pospihold.dto.CashierMsgDto;
import com.pospi.pospihold.dto.GoodsDto;
import com.pospi.pospihold.dto.MenuDto;
import com.pospi.pospihold.dto.PayBeen;
import com.pospi.pospihold.dto.PrintBeen;
import com.pospi.pospihold.dto.ReturnDto;
import com.pospi.pospihold.greendao.PayBeenDao;
import com.pospi.pospihold.greendao.PrintBeenDao;
import com.pospi.pospihold.http.LoadServer;
import com.pospi.pospihold.ui.MainActivity;
import com.pospi.pospihold.ui.base.BaseActivity;
import com.pospi.pospihold.util.Api;
import com.pospi.pospihold.util.DownUtil;
import com.pospi.pospihold.util.PareseJson;
import com.pospi.pospihold.util.SaveMenuInfo;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class CashierLoginActivity extends BaseActivity {

    @Bind(R.id.lv_cashier)
    ListView lvCashier;

    private CashierLoginAdapter adapter;
    private List<CashierMsgDto> msgDtos;
    private GoodsDao goodsDao;

    private Handler m_handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 22:
                    getMenuData();
                    break;
                case 23:
                    getgroupMsg();
                    break;
                case 24:
                    downMsg();
                    break;

            }
        }
    };
    private Dialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_cashier_login);
        ButterKnife.bind(this);
        setTitle("收银员选择");
        setBackVisible(false);
        showDialog("正在下载商品信息");
        DownUtil downUtil = new DownUtil(this);
        downUtil.downYs();
        downUtil.downYsz();
        downUtil.downPay();
        downprint();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg = Message.obtain();
                msg.what = 22;
                m_handler.sendMessage(msg);
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg = Message.obtain();
                msg.what = 23;
                m_handler.sendMessage(msg);
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg = Message.obtain();
                msg.what = 24;
                m_handler.sendMessage(msg);
            }
        }).start();


        lvCashier.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                inputPwd(position);
            }
        });

    }

    public void showDialog(String msg) {
        if (dialog == null) {
            dialog = WaitingDialog.createLoadingDialog(CashierLoginActivity.this, msg);
            dialog.show();
        }
    }

    public void closeDialog() {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }


    /**
     * 进入界面之后联网获取数据下载商品数据库
     */
    public void getMenuData() {

        goodsDao = new GoodsDao(getApplicationContext());

        final RequestParams params = new RequestParams();//实例化后存入键值对

        LoadServer.getConnect(getApplicationContext(), Api.SYNC_MENUS, params, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int code, Header[] headers, byte[] bytes) {
                        if (code == 200) {
                            Log.i("responseBody", new String(bytes));
                            try {
                                JSONObject object = new JSONObject(new String(bytes));
                                ReturnDto loginReturnDto = new ReturnDto();
                                loginReturnDto.setResult(object.getInt("Result"));
                                loginReturnDto.setMessage(object.getString("Message"));


                                Gson gson = new Gson();
                                List<GoodsDto> dtos = gson.fromJson(object.getString("Value"), new TypeToken<List<GoodsDto>>() {
                                }.getType());
                                Log.i("dto.size", dtos.size() + "位");

                                goodsDao.addGoods(dtos);


                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

                    }
                }
        );
    }

    public void getgroupMsg() {
        SharedPreferences preferences = getSharedPreferences("StoreMessage", MODE_PRIVATE);
        String shopid = preferences.getString("Id", "");
        RequestParams params = new RequestParams();
        params.put("value", shopid);
        LoadServer.getConnect(getApplicationContext(), Api.SYNCCATEGORY, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int dd, Header[] headers, byte[] bytes) {
                String response = new String(bytes);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    Log.i("Value", jsonObject.getString("Value"));
                    List<MenuDto> menuDtos = new Gson().fromJson(jsonObject.getString("Value"),
                            new TypeToken<List<MenuDto>>() {
                            }.getType());
                    SaveMenuInfo.saveAsJson(getApplicationContext(), menuDtos);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });
    }


    public void inputPwd(final int position) {

        final EditText editText = new EditText(this);
        editText.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD);
        editText.setTransformationMethod(PasswordTransformationMethod.getInstance());

        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("收银员账号：" + msgDtos.get(position).getNumber())
                .setMessage("请输入密码:")
                .setView(editText).
                        setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                judgePwd(editText, position);
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }


    //收银员登录的时候判断账号密码是否正确
    public void judgePwd(EditText text, int position) {
        if (msgDtos.get(position).getPwd().equals(text.getText().toString())) {
            Toast.makeText(getApplicationContext(), "收银员登录成功", Toast.LENGTH_SHORT).show();
            SharedPreferences.Editor editor = getSharedPreferences("islogin", MODE_PRIVATE).edit();
            editor.putBoolean("islogin", true);
            editor.putInt("which", position);
            editor.apply();


            startActivity(MainActivity.class);
            finish();

        } else {
            Toast.makeText(getApplicationContext(), "密码错误请重新输入！", Toast.LENGTH_SHORT).show();
        }
    }

    public void downMsg() {
        RequestParams params = new RequestParams();
        params.put("value", getSharedPreferences("StoreMessage", MODE_PRIVATE).getString("Id", ""));
        LoadServer.getConnect(getApplicationContext(), Api.SYNCCASHIER, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.d("value", new String(bytes));
                SharedPreferences.Editor editor = getSharedPreferences("cashierMsgDtos", MODE_PRIVATE).edit();
                editor.putString("cashierMsgDtos", new String(bytes));
                editor.apply();
                msgDtos = new PareseJson().parese(new String(bytes));
                adapter = new CashierLoginAdapter(getApplicationContext(), msgDtos);
                lvCashier.setAdapter(adapter);
                closeDialog();
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                showToast("加载失败，请稍后重试");
            }
        });
    }
    public void downprint(){
        RequestParams params = new RequestParams();
        params.put("value", getSharedPreferences("StoreMessage", MODE_PRIVATE).getString("Id", ""));
        LoadServer.getConnect(getApplicationContext(), Api.GET_PRINT_MSG, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.d("print", new String(bytes));
                try {
                    JSONObject object = new JSONObject(new String(bytes));
                    JSONArray array = object.getJSONArray("Value");
                    List<PrintBeen> beens = new Gson().fromJson(array.toString(), new TypeToken<List<PrintBeen>>() {
                    }.getType());
                    PrintBeenDao dao = App.getInstance().getDaoSession().getPrintBeenDao();
                    dao.deleteAll();
                    dao.insertInTx(beens);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });
    }




}
